import cv2


class ConnectCamera:
    def __init__(self, ip, port=554, codec="h264", username="admin", password="hwtc@666", time=0):
        self.username = username
        self.password = password
        self.ip = ip
        self.port = port
        self.codec = codec
        self.channel = 1
        self.subtype = "0"
        self.url = f"rtsp://{self.username}:{self.password}@{self.ip}:{self.port}/{self.codec}/ch{self.channel}/{self.subtype}/av_stream"
        self.timer = time

    def init_camera(self):
        print(self.url)
        cap = cv2.VideoCapture(self.url)
        print(cap.isOpened())
        return cap

    def open_camera(self):
        cap = self.init_camera()
        if not cap.isOpened():
            print("Failed to connect camera")
            exit()
        n = 0
        while True:
            """ 每三十帧处理一次图片 """
            n += 1
            # 如果是否有定时取帧
            if self.timer:
                if n < self.timer * 30:
                    _, _ = cap.read()
                else:
                    n = n % 30
                    ret, frame = cap.read()
                    if not ret:
                        break
                    cv2.imshow('frame', frame)
            else:
                ret, frame = cap.read()
                if not ret:
                    break
                cv2.imshow('frame', frame)

            if cv2.waitKey(1) == ord('q'):
                break

        cap.release()
        cv2.destroyAllWindows()


if __name__ == '__main__':
    # ip = "192.168.1.64"
    # cam = ConnectCamera(ip)
    # cam.open_camera()
    ip = "http://10.8.18.239"
    port = 534
    codec = "h264"
    username = "admin"
    timer = 0
    password = "hwtc@666"
    cam = ConnectCamera(ip, port, codec, username, password, timer)
    cam.open_camera()